package com.scrat.sensorlist;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.rv_list)
    RecyclerView rvList;

    private SensorManager sensorManager;
    private SensorAdapter sensorAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mainToolbar.setTitle(R.string.app_name);
        mainToolbar.setBackgroundResource(R.color.colorPrimary);
        setSupportActionBar(mainToolbar);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
        List<Sensor> newList = new ArrayList<>(sensorList);

        Collections.sort(newList, new Comparator<Sensor>() {
            @Override
            public int compare(Sensor o1, Sensor o2) {
                return o1.getType() - o2.getType();
            }
        });

        sensorAdapter = new SensorAdapter(newList);


        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        rvList.setAdapter(sensorAdapter);

        sensorAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.d(TAG, "position:" + position);
                Sensor sensor = (Sensor) adapter.getItem(position);

                Intent intent = new Intent(getApplicationContext(), SensorActivity.class);
                intent.putExtra(SensorActivity.SENSOR_TYPE, sensor.getType());
                startActivity(intent);
            }
        });


    }


}
